from flask import jsonify, request
from app.api.v1 import bp
from app.models.marine_area import MarineArea
from app.models.ecological_indicator import EcologicalIndicator
from app.models.industry_score import IndustryScore
from app import db

# 获取所有海域列表
@bp.route('/marine-areas', methods=['GET'])
def get_marine_areas():
    """
    获取所有海域基本信息
    返回: 所有海域的列表，包含id、名称、位置等基本信息
    """
    marine_areas = MarineArea.query.all()
    return jsonify([{
        'id': area.id,
        'name': area.area_name,
        'location': {
            'lat': float(area.location_lat),
            'lng': float(area.location_lng)
        },
        'description': area.description,
        'scores': [{
            'type': score.industry_type,
            'value': float(score.score),
            'date': score.evaluation_date.strftime('%Y-%m-%d')
        } for score in area.scores]
    } for area in marine_areas])

# 获取单个海域详情
@bp.route('/marine-areas/<int:id>', methods=['GET'])
def get_marine_area(id):
    """
    获取指定海域的详细信息
    参数: id - 海域ID
    返回: 指定海域的详细信息，包括环境数据、评分等
    """
    area = MarineArea.query.get_or_404(id)
    return jsonify({
        'id': area.id,
        'name': area.area_name,
        'location': {
            'lat': float(area.location_lat),
            'lng': float(area.location_lng)
        },
        'description': area.description,
        'scores': [{
            'type': score.industry_type,
            'value': float(score.score),
            'date': score.evaluation_date.strftime('%Y-%m-%d')
        } for score in area.scores],
        'indicators': [{
            'water_quality': float(indicator.water_quality),
            'biodiversity': float(indicator.biodiversity),
            'pollution_index': float(indicator.pollution_index),
            'resource_reserve': float(indicator.resource_reserve),
            'environmental_capacity': float(indicator.environmental_capacity),
            'date': indicator.measurement_date.strftime('%Y-%m-%d')
        } for indicator in area.indicators]
    })

# 获取所有生态指标
@bp.route('/ecological-indicators', methods=['GET'])
def get_all_ecological_indicators():
    indicators = EcologicalIndicator.query.all()
    return jsonify([{
        'id': indicator.id,
        'marine_area_id': indicator.marine_area_id,
        'water_quality': float(indicator.water_quality),
        'biodiversity': float(indicator.biodiversity),
        'pollution_index': float(indicator.pollution_index),
        'resource_reserve': float(indicator.resource_reserve),
        'environmental_capacity': float(indicator.environmental_capacity),
        'measurement_date': indicator.measurement_date.strftime('%Y-%m-%d')
    } for indicator in indicators])

# 获取指定海域的生态指标
@bp.route('/ecological-indicators/<int:id>', methods=['GET'])
def get_ecological_indicators(id):
    indicators = EcologicalIndicator.query.filter_by(marine_area_id=id).all()
    return jsonify([{
        'id': indicator.id,
        'water_quality': float(indicator.water_quality),
        'biodiversity': float(indicator.biodiversity),
        'pollution_index': float(indicator.pollution_index),
        'resource_reserve': float(indicator.resource_reserve),
        'environmental_capacity': float(indicator.environmental_capacity),
        'measurement_date': indicator.measurement_date.strftime('%Y-%m-%d')
    } for indicator in indicators])

# 获取所有产业评分
@bp.route('/industry-scores', methods=['GET'])
def get_all_industry_scores():
    scores = IndustryScore.query.all()
    return jsonify([{
        'id': score.id,
        'marine_area_id': score.marine_area_id,
        'industry_type': score.industry_type,
        'score': float(score.score),
        'evaluation_date': score.evaluation_date.strftime('%Y-%m-%d')
    } for score in scores])

# 获取指定海域的产业评分
@bp.route('/industry-scores/<int:id>', methods=['GET'])
def get_industry_scores(id):
    scores = IndustryScore.query.filter_by(marine_area_id=id).all()
    return jsonify([{
        'id': score.id,
        'industry_type': score.industry_type,
        'score': float(score.score),
        'evaluation_date': score.evaluation_date.strftime('%Y-%m-%d')
    } for score in scores])

@bp.route('/marine-areas/<int:id>/scores', methods=['GET'])
def get_area_scores(id):
    """
    获取指定海域的产业评分
    参数: id - 海域ID
    返回: 该海域的各项产业评分数据和平均分
    """
    print(f"Requesting scores for area ID: {id}")  # 添加日志
    area = MarineArea.query.get_or_404(id)
    scores = IndustryScore.query.filter_by(marine_area_id=id).all()
    
    # 计算平均分
    avg_score = sum(float(score.score) for score in scores) / len(scores) if scores else 0
    
    response_data = {
        'area_name': area.area_name,
        'scores': [{
            'industry_type': score.industry_type,
            'score': float(score.score),
            'evaluation_date': score.evaluation_date.strftime('%Y-%m-%d')
        } for score in scores],
        'average_score': round(avg_score, 2)  # 保留两位小数
    }
    print(f"Response data: {response_data}")  # 添加日志
    return jsonify(response_data)